﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Sso.Models;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Sso.Controllers
{
    /// <summary>
    /// 统一授权验证入口
    /// </summary>
    public class AuthController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }


        private IOptions<Audience> _settings;

        public AuthController(IOptions<Audience> settings)
        {
            this._settings = settings;
        }

        public IActionResult AuthLogin(LoginViewModel model)
        {

            if (string.IsNullOrWhiteSpace(model.Name))
            {
                return Ok("登录名称不能为空");
            }
            if (string.IsNullOrWhiteSpace(model.Password))
            {
                return Ok("登录密码不能为空");
            }


            var now = DateTime.UtcNow;

            var claims = new Claim[]
            {
                    new Claim(JwtRegisteredClaimNames.Sub, model.Name), // 姓名
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //唯一的表示
                    new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)  // 发行时间
            };

            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_settings.Value.Secret));

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,
                ValidateIssuer = true,
                ValidIssuer = _settings.Value.Iss,
                ValidateAudience = true,
                ValidAudience = _settings.Value.Aud,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero,
                RequireExpirationTime = true,

            };

            var jwt = new JwtSecurityToken(
                   issuer: _settings.Value.Iss,
                   audience: _settings.Value.Aud,
                   claims: claims,
                   notBefore: now,
                   expires: now.Add(TimeSpan.FromMinutes(2)),
                   signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
               );
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            var responseJson = new
            {
                access_token = encodedJwt,
                expires_in = (int)TimeSpan.FromMinutes(2).TotalSeconds
            };

            return Json(responseJson);
        }
    }

    public class Audience
    {
        public string Secret { get; set; }
        public string Iss { get; set; }
        public string Aud { get; set; }
    }
}
